import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Select, Space, Pagination, Modal, message, Descriptions } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { FileTextOutlined, UserOutlined, CalendarOutlined, TagOutlined, AppstoreOutlined, ClusterOutlined } from '@ant-design/icons';

const { Option } = Select;

const initialData = [
  { key: 1, title: '文章标题示例', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 2, title: '对于年检，你焦虑吗？', channel: '小程序', category: '今日热点', type: '视频', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 3, title: '针对新引进成都大学生推出租房补贴', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 4, title: '中小微、个体户，这些扶持政策必收藏！', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 5, title: '冬奥盛宴上有哪些黑科技日常的踩', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 6, title: '冬奥会临近，疫情防控有哪...', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 7, title: '浙江新增境外输入确诊病例例', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 8, title: '印度热浪创纪录拉响新高科技', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 9, title: '电价下行成必然逻辑，技术实事求是', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 10, title: '2022年货币市场冰火', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
  { key: 11, title: '已有许多为什么突然247亿下注销新规', channel: '小程序', category: '今日热点', type: '图文', keyword: '年检', author: '管理员', date: '2022-01-23' },
];

export default function ArticlePublish() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [data, setData] = useState(initialData);
  const [searchTitle, setSearchTitle] = useState("");
  const [searchType, setSearchType] = useState("");
  const [filteredData, setFilteredData] = useState(initialData);
  const navigate = useNavigate();
  const location = useLocation();
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailData, setDetailData] = useState(null);

  // 新增文章后自动添加
  useEffect(() => {
    if (location.state && location.state.newArticle) {
      setData(prev => [{ ...location.state.newArticle, key: Date.now() }, ...prev]);
      // 清除state避免重复添加
      window.history.replaceState({}, document.title);
    }
  }, [location.state]);

  // 查询功能
  const handleSearch = () => {
    setFilteredData(
      data.filter(item => {
        const matchTitle = searchTitle ? item.title.includes(searchTitle) : false;
        const matchType = searchType ? item.type === searchType : false;
        return matchTitle || matchType;
      })
    );
  };

  // 重置功能
  const handleReset = () => {
    setSearchTitle("");
    setSearchType("");
    setFilteredData(data);
  };

  // 保证数据变化时同步过滤
  useEffect(() => {
    setFilteredData(data);
  }, [data]);

  // 单条删除
  const handleDelete = (key) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这篇文章吗？',
      onOk() {
        setData(prevData => prevData.filter(item => item.key !== key));
        message.success('删除成功');
      },
    });
  };

  const showDetail = (record) => {
    setDetailData(record);
    setDetailVisible(true);
  };

  const columns = [
    { title: '文章标题', dataIndex: 'title', key: 'title', width: 220, render: (text) => <span style={{fontWeight:500}}>{text}</span> },
    { title: '发布渠道', dataIndex: 'channel', key: 'channel', width: 100 },
    { title: '发布频道', dataIndex: 'category', key: 'category', width: 100 },
    { title: '文章类型', dataIndex: 'type', key: 'type', width: 100 },
    { title: '关键词', dataIndex: 'keyword', key: 'keyword', width: 100 },
    { title: '发布人', dataIndex: 'author', key: 'author', width: 100 },
    { title: '发送时间', dataIndex: 'date', key: 'date', width: 120 },
    { title: '操作', key: 'action', width: 120, render: (_, record) => (
        <Space>
          <a onClick={() => showDetail(record)}>详情</a>
          <a style={{color:'#f5222d'}} onClick={() => handleDelete(record.key)}>删除</a>
        </Space>
      ) },
  ];

  // 批量删除
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的文章');
      return;
    }
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 篇文章吗？`,
      onOk() {
        setData(data.filter(item => !selectedRowKeys.includes(item.key)));
        setSelectedRowKeys([]);
        message.success('删除成功');
      },
    });
  };

  return (
    <div style={{padding:32, background:'#f5f7fa', minHeight:'100vh'}}>
      <Card style={{maxWidth:1200, margin:'0 auto', borderRadius:12, boxShadow:'0 2px 8px rgba(0,0,0,0.04)'}}>
        <div style={{display:'flex', alignItems:'center', marginBottom:24}}>
          <Button onClick={()=>navigate('/dashboard/enterprise')} style={{marginRight:16, borderRadius:6}}>返回</Button>
          <div style={{fontWeight:700, fontSize:20, display:'flex', alignItems:'center'}}>
            <div style={{width:4, height:22, background:'#3B5BDB', borderRadius:2, marginRight:10}}></div>
            文章发布管理
          </div>
        </div>
        <div style={{marginBottom:20, display:'flex', gap:16, alignItems:'center'}}>
          <Input value={searchTitle} onChange={e=>setSearchTitle(e.target.value)} placeholder="请输入文章标题" style={{width:260, borderRadius:6}} allowClear />
          <Select value={searchType} onChange={v=>setSearchType(v)} placeholder="请选择类型" style={{width:180, borderRadius:6}} allowClear>
            <Option value="图文">图文</Option>
            <Option value="视频">视频</Option>
          </Select>
          <Button type="primary" style={{borderRadius:6, width:80}} onClick={handleSearch}>查询</Button>
          <Button style={{borderRadius:6, width:80}} onClick={handleReset}>重置</Button>
          <div style={{flex:1}}></div>
          <Button type="primary" style={{borderRadius:6, width:90, marginRight:8}} onClick={()=>navigate('/article/create')}>新增</Button>
          <Button danger style={{borderRadius:6, width:90}} onClick={handleBatchDelete}>批量删除</Button>
        </div>
        <Table
          rowSelection={{selectedRowKeys,onChange:setSelectedRowKeys}}
          columns={columns}
          dataSource={filteredData}
          pagination={false}
          bordered
          style={{background:'#fff', borderRadius:8}}
        />
        <div style={{marginTop:24, textAlign:'right'}}>
          <Pagination total={data.length} pageSize={10} showSizeChanger={false} />
        </div>
      </Card>
      <Modal
        open={detailVisible}
        title={null}
        footer={null}
        onCancel={() => setDetailVisible(false)}
        width={600}
        bodyStyle={{padding:32, borderRadius:16, background:'#f7f9fa'}}
      >
        {detailData && (
          <div style={{ background:'#fff', borderRadius:12, boxShadow:'0 2px 8px rgba(0,0,0,0.06)', padding:32 }}>
            <div style={{ display:'flex', alignItems:'center', marginBottom:24 }}>
              <FileTextOutlined style={{ fontSize:32, color:'#3B5BDB', marginRight:16 }} />
              <div>
                <div style={{ fontSize:22, fontWeight:700, color:'#222' }}>{detailData.title}</div>
                <div style={{ color:'#888', fontSize:14, marginTop:4 }}>{detailData.keyword}</div>
              </div>
            </div>
            <Descriptions column={1} labelStyle={{fontWeight:600, color:'#555'}} contentStyle={{color:'#222'}}>
              <Descriptions.Item label={<span><AppstoreOutlined style={{marginRight:6}}/>发布渠道</span>}>{detailData.channel}</Descriptions.Item>
              <Descriptions.Item label={<span><ClusterOutlined style={{marginRight:6}}/>发布频道</span>}>{detailData.category}</Descriptions.Item>
              <Descriptions.Item label={<span><TagOutlined style={{marginRight:6}}/>文章类型</span>}>{detailData.type}</Descriptions.Item>
              <Descriptions.Item label={<span><UserOutlined style={{marginRight:6}}/>发布人</span>}>{detailData.author}</Descriptions.Item>
              <Descriptions.Item label={<span><CalendarOutlined style={{marginRight:6}}/>发送时间</span>}>{detailData.date}</Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>
    </div>
  );
} 